{% extends "base.html" %}

{% block title %}我的收藏 - 墨韵图书共享平台{% endblock %}

{% block content %}
<div class="container py-4">
    <div class="card ink-card mb-4">
        <div class="card-header ink-header">
            <h4 class="mb-0">
                <i class="fas fa-bookmark me-2"></i>我的收藏帖子
            </h4>
        </div>
        <div class="card-body">
            {% if posts.items %}
                {% for post in posts.items %}
                <div class="card ink-card mb-4 post-card">
                    <div class="card-body">
                        <div class="d-flex">
                            <!-- 作者头像 -->
                            <div class="me-3">
                                {% if post.author.avatar and post.author.avatar != 'default.png' %}
                                <img src="{{ url_for('static', filename='avatars/' + post.author.avatar) }}" 
                                     class="user-avatar" alt="{{ post.author.username }}"
                                     onerror="handleImageError(this)">
                                {% else %}
                                <div class="default-avatar">{{ post.author.username[0]|upper }}</div>
                                {% endif %}
                            </div>
                            
                            <!-- 帖子内容 -->
                            <div class="flex-grow-1">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <h5 class="card-title mb-0">
                                        <a href="{{ url_for('view_post', post_id=post.id) }}" class="text-decoration-none">
                                            {{ post.title }}
                                        </a>
                                    </h5>
                                    {% if post.circle %}
                                    <span class="badge bg-primary">
                                        <i class="fas fa-users me-1"></i>{{ post.circle.name }}
                                    </span>
                                    {% endif %}
                                </div>
                                
                                <div class="post-meta mb-2">
                                    <small class="text-muted">
                                        <i class="fas fa-user me-1"></i>{{ post.author.username }} · 
                                        <i class="fas fa-clock me-1"></i>{{ post.created_at.strftime('%Y-%m-%d %H:%M') }}
                                    </small>
                                </div>
                                
                                <div class="post-content mb-3">
                                    {{ post.content|striptags|truncate(200) }}
                                </div>
                                
                                <div class="post-actions">
                                    <button class="btn btn-sm {% if post.id in liked_post_ids %}btn-primary{% else %}btn-outline-primary{% endif %} me-2" 
                                            onclick="toggleLike('{{ post.id }}', this)" id="like-btn-{{ post.id }}">
                                        <i class="fas fa-thumbs-up"></i>
                                        <span id="like-count-{{ post.id }}">{{ post.likes }}</span>
                                    </button>
                                    <button class="btn btn-sm btn-primary me-2" 
                                            onclick="toggleFavorite('{{ post.id }}', this)" id="favorite-btn-{{ post.id }}">
                                        <i class="fas fa-bookmark"></i>
                                        <span id="favorite-count-{{ post.id }}">{{ post.favorites }}</span>
                                    </button>
                                    <a href="{{ url_for('view_post', post_id=post.id) }}" class="btn btn-sm btn-outline-secondary">
                                        <i class="fas fa-eye"></i> 查看详情
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                {% endfor %}
                
                <!-- 分页 -->
                {% if posts.pages > 1 %}
                <nav aria-label="Page navigation" class="mt-4">
                    <ul class="pagination justify-content-center">
                        {% if posts.has_prev %}
                        <li class="page-item">
                            <a class="page-link" href="{{ url_for('favorite_posts', page=posts.prev_num) }}">
                                <i class="fas fa-chevron-left"></i>
                            </a>
                        </li>
                        {% endif %}
                        
                        {% for page in posts.iter_pages() %}
                            {% if page %}
                                <li class="page-item {% if page == posts.page %}active{% endif %}">
                                    <a class="page-link" href="{{ url_for('favorite_posts', page=page) }}">
                                        {{ page }}
                                    </a>
                                </li>
                            {% else %}
                                <li class="page-item disabled">
                                    <span class="page-link">...</span>
                                </li>
                            {% endif %}
                        {% endfor %}
                        
                        {% if posts.has_next %}
                        <li class="page-item">
                            <a class="page-link" href="{{ url_for('favorite_posts', page=posts.next_num) }}">
                                <i class="fas fa-chevron-right"></i>
                            </a>
                        </li>
                        {% endif %}
                    </ul>
                </nav>
                {% endif %}
            {% else %}
                <div class="text-center py-5">
                    <i class="fas fa-bookmark fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">您还没有收藏任何帖子</h5>
                    <a href="{{ url_for('forum') }}" class="btn btn-primary mt-3">
                        <i class="fas fa-arrow-left me-2"></i>浏览帖子
                    </a>
                </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- Toast 容器，用于显示消息通知 -->
<div class="toast-container position-fixed bottom-0 end-0 p-3"></div>

<style>
.ink-card {
    border: none;
    border-radius: 10px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    transition: all 0.3s ease;
}

.ink-card:hover {
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.ink-header {
    background-color: #f8f9fa;
    border-bottom: none;
    padding: 1.5rem;
}

.user-avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    object-fit: cover;
}

.default-avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background: #e9ecef;
    color: #6c757d;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 1.2rem;
}

.post-card {
    transition: transform 0.2s ease;
}

.post-card:hover {
    transform: translateY(-2px);
}

.pagination .page-link {
    border: none;
    margin: 0 2px;
    border-radius: 5px;
    color: #6c757d;
}

.pagination .page-item.active .page-link {
    background-color: #0d6efd;
}
</style>

{% block scripts %}
<script>
function handleImageError(img) {
    img.onerror = null;  // 防止循环
    img.src = "{{ url_for('static', filename='images/default_cover.jpg') }}";
}

function toggleLike(postId, btn) {
    fetch(`/post/${postId}/like`, {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const likeCount = document.getElementById(`like-count-${postId}`);
            likeCount.textContent = data.likes;
            
            if (data.action === 'liked') {
                btn.classList.remove('btn-outline-primary');
                btn.classList.add('btn-primary');
                showToast('点赞成功', '您已成功点赞该帖子');
            } else {
                btn.classList.remove('btn-primary');
                btn.classList.add('btn-outline-primary');
                showToast('取消点赞', '您已取消点赞该帖子');
            }
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('操作失败', '请稍后重试', 'danger');
    });
}

function toggleFavorite(postId, btn) {
    fetch(`/post/${postId}/favorite`, {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应不正常');
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            const favoriteCount = document.getElementById(`favorite-count-${postId}`);
            favoriteCount.textContent = data.favorites;
            
            if (data.action === 'unfavorited') {
                // 从收藏列表中移除帖子
                const postCard = btn.closest('.post-card');
                postCard.style.transition = 'all 0.3s ease';
                postCard.style.opacity = '0';
                postCard.style.transform = 'scale(0.8)';
                
                setTimeout(() => {
                    postCard.remove();
                    
                    // 如果没有更多帖子，显示空状态
                    if (document.querySelectorAll('.post-card').length === 0) {
                        location.reload();
                    }
                }, 300);
                
                showToast('取消收藏', '帖子已从您的收藏中移除');
            } else {
                showToast('收藏成功', '帖子已添加到您的收藏');
            }
        } else {
            showToast('操作失败', data.message || '请稍后重试', 'danger');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('操作失败', '请稍后重试', 'danger');
    });
}

// 显示提示信息
function showToast(title, message, type = 'primary') {
    try {
        // 检查 bootstrap 对象是否存在
        if (typeof bootstrap === 'undefined') {
            console.error('Bootstrap not loaded');
            alert(title + ': ' + message);
            return;
        }
        
        // 创建 toast 元素
        const toastEl = document.createElement('div');
        toastEl.className = `toast align-items-center text-white bg-${type} border-0`;
        toastEl.setAttribute('role', 'alert');
        toastEl.setAttribute('aria-live', 'assertive');
        toastEl.setAttribute('aria-atomic', 'true');
        
        // 设置自动隐藏时间
        toastEl.setAttribute('data-bs-delay', '3000');
        
        // 添加内容
        toastEl.innerHTML = 
            '<div class="d-flex">' +
                '<div class="toast-body">' +
                    '<strong>' + title + '</strong>: ' + message +
                '</div>' +
                '<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>' +
            '</div>';
        
        // 添加到容器
        const toastContainer = document.querySelector('.toast-container');
        if (toastContainer) {
            toastContainer.appendChild(toastEl);
        } else {
            // 如果没有容器，创建一个
            const newContainer = document.createElement('div');
            newContainer.className = 'toast-container position-fixed bottom-0 end-0 p-3';
            newContainer.appendChild(toastEl);
            document.body.appendChild(newContainer);
        }
        
        // 显示 toast
        const toast = new bootstrap.Toast(toastEl);
        toast.show();
    } catch (error) {
        console.error('Error showing toast:', error);
        alert(title + ': ' + message);
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查是否支持 Bootstrap
    if (typeof bootstrap === 'undefined') {
        console.warn('Bootstrap not loaded. Some features may not work correctly.');
    }
});
</script>
{% endblock %} 